package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum.OrderType;
import com.fz.us.base.bean.BaseEnum.StateEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.joint.base.entity.Company;
import com.joint.base.entity.FileManage;
import com.joint.base.entity.Users;
import com.joint.base.service.AuthCodeService;
import com.joint.base.service.CompanyService;
import com.joint.base.service.FileManageService;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;
import com.joint.base.util.excel.ExcelUtil;
import com.joint.base.util.excel.ExportExcel;
import com.joint.base.util.excel.ImportExcel;

import com.joint.web.action.BaseAdminAction;
import com.mongodb.gridfs.GridFSDBFile;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by amin on 2015/3/5.
 */
@ParentPackage("com")
public class AjaxImportAction extends BaseAdminAction {

    @Resource
    private CompanyService companyService;

    @Resource
    private UsersService usersService;
    @Resource
    private DictService dictService;
    @Resource
    private FileManageService fileManageService;
    @Resource
    private AuthCodeService authCodeService;

    private File Filedata;
    private String Filename;
    private String FiledataFileName;
    private String FiledataContentType;
    private String csvname;
    private String idList;

    private static Logger log = LoggerFactory.getLogger(AjaxImportAction.class);

    /**
     * 下载视图
     */
    public String datalist(){
        pager = new Pager();
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(OrderType.desc);
        Company company=usersService.getCompanyByUser();
        Map<String,Object> map= Maps.newHashMap();
        map.put("name",".xls");
        pager=fileManageService.findByPagerAndCompany(pager, null, company,map);
        List<FileManage> fileManageList= (List<FileManage>) pager.getList();
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(FileManage fileManage:fileManageList){
            rMap = new HashMap<String, Object>();
           if(StringUtils.isNotEmpty(fileManage.getTargetClass())){
               rMap.put("id",fileManage.getGridId());
               rMap.put("name",fileManage.getName());
               rMap.put("createDate", DataUtil.DateToString(fileManage.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
           }
            dataRows.add(JSONObject.fromObject(rMap));
        }
        long total =pager.getTotalCount();
        if(total%rows==0){
            total = total/rows;
        }else{
            if(total<rows){
                total = 1;
            }else{
                total = total/rows + 1;
            }
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",total);
        data.put("records",pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 下载文件
     */
    public String download() throws IOException{
        GridFSDBFile file = null;
        String fileName=null;
        if(StringUtils.isNotEmpty(keyId)){
            if(fileManageService.get(keyId) != null){
                file = gridFSGet(fileManageService.get(keyId).getGridId());
            }else {
                file = gridFSGet(keyId);
            }
            OutputStream out = null;
            HttpServletResponse response = getTheResponse();
            response.setContentType(file.getContentType());
            fileName=new String(file.getFilename().getBytes("iso-8859-1"),"UTF-8");
            try {
                response.setHeader("Content-Disposition","attachment;filename="+fileName);
                response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(file.getFilename().getBytes("UTF-8"), "iso-8859-1") + "\"");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            out = response.getOutputStream();
            file.writeTo(out);
        }
        return null;
    }



    public String list(){
        return "list";
    }

    public String dialog(){
        return "dialog";
    }

    public String getCsvname() {
        return csvname;
    }

    public void setCsvname(String csvname) {
        this.csvname = csvname;
    }

    public File getFiledata() {
        return Filedata;
    }

    public void setFiledata(File filedata) {
        Filedata = filedata;
    }

    public String getFilename() {
        return Filename;
    }

    public void setFilename(String filename) {
        Filename = filename;
    }

    public String getFiledataFileName() {
        return FiledataFileName;
    }

    public void setFiledataFileName(String filedataFileName) {
        FiledataFileName = filedataFileName;
    }

    public String getFiledataContentType() {
        return FiledataContentType;
    }

    public void setFiledataContentType(String filedataContentType) {
        FiledataContentType = filedataContentType;
    }

    public String getIdList() {
        return idList;
    }

    public void setIdList(String idList) {
        this.idList = idList;
    }
}
